<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="发布人手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入发布人手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回答发布时间">
        <el-date-picker
          v-model="daterangePublishTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-back" size="mini" @click="toQues">返回问题页面</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['space:answer:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['space:answer:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['space:answer:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['space:answer:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <!-- 问题信息展示区域 -->
      <div class="question-info" v-if="$route.query.quesId">
        <el-row :gutter="20" style="margin-bottom: 20px; background-color: #f8f8f9; padding: 10px 0; border-radius: 4px;">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">问题标题：</span>
              <span class="value">{{ $route.query.quesTitle}}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item" style="text-align: right;">
              <span class="label">回答数量:</span>
              <span class="value">共计{{ $route.query.replyCount }}条</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="answerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="回答ID" align="center" prop="id" />-->
      <el-table-column label="回答内容" align="center" prop="content" />
      <el-table-column label="回答发布人" align="center" prop="publisher" />
      <el-table-column label="发布人手机号" align="center" prop="phone" />
      <el-table-column label="回答发布时间" align="center" prop="publishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['space:answer:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['space:answer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改查看回答对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="回答内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="回答发布人" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入回答发布人" />
        </el-form-item>
        <el-form-item label="发布人手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入发布人手机号" />
        </el-form-item>
        <el-form-item label="回答发布时间" prop="publishTime">
          <el-date-picker clearable
            v-model="form.publishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择回答发布时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnswer, getAnswer, delAnswer, addAnswer, updateAnswer } from "@/api/space/answer";
import { getQues, updateQues } from '@/api/space/ques'
import { parseTime } from '../../../utils/ruoyi'

export default {
  name: "Answer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查看回答表格数据
      answerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 回答发布时间时间范围
      daterangePublishTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        phone: null,
        publishTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
    };
  },
  created() {
    this.getList();

    // 添加路由参数监听器，当 quesId 变化时重新加载数据
    this.$watch(
      () => this.$route.query.quesId,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          // 重置分页到第一页
          this.queryParams.pageNum = 1;
          // 清空过滤条件
          this.daterangePublishTime = [];
          this.queryParams.phone = null;
          // 重新加载数据
          this.getList();
        }
      }
    );
  },
  // 添加 activated 生命周期钩子，在从缓存中激活组件时刷新数据
  activated() {
    // 在使用 keep-alive 的情况下，从其他页面回到此页面时会触发
    this.getList();
  },
  // 在路由进入时也刷新数据
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 如果路由参数中有问题ID，则刷新列表
      if (to.query.quesId) {
        vm.getList();
      }
    });
  },
  // 监听路由参数变化
  beforeRouteUpdate(to, from, next) {
    // 处理同一组件内的路由变化
    if (to.query.quesId !== from.query.quesId) {
      // 先允许路由变化
      next();
      // 然后重新加载数据
      this.getList();
    } else {
      next();
    }
  },
  methods: {
    //日期格式化
    parseTime,
    /** 返回问题页面 */
    toQues() {
      // 获取当前的问题ID，用于在返回前进行必要的数据更新
      const quesId = this.$route.query.quesId;

      if (quesId) {
        // 先获取最新的问题数据
        getQues(quesId).then(response => {
          if (response.data) {
            // 获取到最新的问题数据后，再进行页面跳转
            // 这是一种模拟"请求转发"的方式，确保数据是最新的
            this.$router.push({
              path: '/space/ques',
              // 不传递任何查询参数，确保清除缓存状态
              // 如果想携带某些状态，可以在这里添加
            });
          }
        }).catch(() => {
          // 即使获取数据失败，也执行跳转
          this.$router.push({
            path: '/space/ques'
          });
        });
      } else {
        // 如果没有问题ID，直接跳转
        this.$router.push({
          path: '/space/ques'
        });
      }
    },
    /** 查询查看回答列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};

      // 检查是否有传入的问题ID (从URL参数中获取)
      const quesId = this.$route.query.quesId;

      if (quesId) {
        // 如果有问题ID，则添加到查询参数中
        this.queryParams.quesId = quesId; // 添加问题ID到查询参数
      }

      // 处理日期范围参数
      if (null != this.daterangePublishTime && '' != this.daterangePublishTime) {
        this.queryParams.params["beginPublishTime"] = this.daterangePublishTime[0];
        this.queryParams.params["endPublishTime"] = this.daterangePublishTime[1];
      }

      // 每次查询前清空答案列表，确保不会显示旧数据
      this.answerList = [];

      listAnswer(this.queryParams).then(response => {
        let allAnswers = response.rows;

        // 如果有问题ID，则在前端过滤数据
        if (quesId) {
          allAnswers = allAnswers.filter(item => item.quesId == quesId);
          this.total = allAnswers.length; // 更新过滤后的总数

          // 同步更新URL参数中的回答数量
          if (this.$route.query.replyCount != this.total) {
            const query = {...this.$route.query};
            query.replyCount = this.total;

            // 不触发组件重新加载的情况下更新URL参数
            this.$router.replace({
              query
            });

            // 同时更新数据库中的回答数量
            updateQues({
              id: quesId,
              replyCount: this.total
            });
          }
        } else {
          this.total = response.total; // 使用后端返回的总数
        }

        this.answerList = allAnswers;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        content: null,
        publisher: null,
        phone: null,
        publishTime: null,
        quesId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangePublishTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置问题ID
      if (this.$route.query.quesId) {
        this.form.quesId = this.$route.query.quesId;
      }
      this.open = true;
      this.title = "添加查看回答";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAnswer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改查看回答";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 设置问题ID
          if (!this.form.quesId && this.$route.query.quesId) {
            this.form.quesId = this.$route.query.quesId;
          }

          if (this.form.id != null) {
            updateAnswer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAnswer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();

              // 新增回答后，更新问题的回答数量
              this.updateQuesReplyCount(1);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除查看回答编号为"' + ids + '"的数据项？').then(function() {
        return delAnswer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");

        // 删除回答后，更新问题的回答数量
        this.updateQuesReplyCount(-1);
      }).catch(() => {});
    },
    /** 更新问题的回答数量 */
    updateQuesReplyCount(change) {
      // 获取当前问题ID
      const quesId = this.$route.query.quesId;
      if (!quesId) return;

      // 获取问题详情
      getQues(quesId).then(response => {
        if (response.data) {
          const ques = response.data;
          // 计算新的回答数量
          let newReplyCount = (ques.replyCount || 0) + change;
          // 确保不会小于0
          newReplyCount = Math.max(0, newReplyCount);

          // 更新问题的回答数量
          updateQues({
            id: quesId,
            replyCount: newReplyCount
          }).then(() => {
            // 更新URL参数中的回答数量
            const query = {...this.$route.query};
            query.replyCount = newReplyCount;

            // 不触发组件重新加载的情况下更新URL参数
            this.$router.replace({
              query
            });
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('space/answer/export', {
        ...this.queryParams
      }, `answer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
